<template>
    <b-page :topTitle="['账号管理']">
        <div slot="content" class="account-page">
            <div class="account-header">账户管理</div>
                <ul class="account-body">
                    <li>
                        <div>账号/道路运输许可证号</div>
                        <div>{{user || '--'}}</div>
                    </li>
                     <li>
                        <div>负责人姓名</div>
                        <div>{{contactName || '--'}}</div>
                    </li>
                    <li>
                        <div>企业名称</div>
                        <div>{{companyName || '--'}}</div>
                    </li>
                    <li>
                        <div>已绑定手机号</div>
                        <div>{{mobile || '--'}}<Button v-if="mobile" type="text" @click="mobileModal = true">修改手机号</Button></div>
                    </li>
                    <li>
                        <div>密码</div>
                        <div>已设定<Button v-if="mobile" type="text" @click="passwordModal = true">更换密码</Button></div>
                    </li>
                </ul>
                
                <!-- 修改手机号弹框 -->
                <Modal
                    v-model="mobileModal"
                    title="修改手机号"
                    :loading="loadingMobile"
                    @on-ok="submitMobile"
                    @on-visible-change="toggleMobile">
                    <Form ref="formMobile" :model="formMobile" :rules="ruleMobile" :label-width="120">
                        <FormItem label="新绑定手机号:" prop="mobile">
                            <Row :gutter="10">
                                <Col span="21">
                                    <Input v-model="formMobile.mobile" placeholder="请输入需要绑定的手机号"></Input>
                                </Col>
                            </Row>
                        </FormItem>
                        <FormItem label="验证码:" prop="code">
                            <Row :gutter="10">
                                <Col span="14">
                                    <Input v-model="formMobile.code" placeholder="请输入手机号验证码"></Input>
                                </Col>
                                <Col span="7">
                                    <Button type="primary" @click="getCode" v-if="!sendState">发送验证码</Button>
                                    <Button type="text" disabled v-else>{{codeTime}}s后重发</Button>
                                </Col>
                            </Row>
                            
                        </FormItem>
                    </Form>
                </Modal>
                
                <!-- 修改密码弹框 -->
                <Modal
                    v-model="passwordModal"
                    title="更换密码"
                    :loading="loadingPassword"
                    @on-ok="submitPassword"
                    @on-visible-change="togglePassword">
                    <Form ref="formPassword" :model="formPassword" :rules="rulePassword" :label-width="120" class="form-password">
                        <Form-item label="原登录密码" prop="oldPassword">
                            <Input type="password" v-model.trim="formPassword.oldPassword" placeholder="请输入原来的密码"></Input>
                        </Form-item>

                        <common-password :password="formPassword.password" @passwordChange="passwordChange"></common-password>

                        <Form-item label="确认登录密码" prop="passwordRepeat">
                            <Input type="password" v-model.trim="formPassword.passwordRepeat" placeholder="再次输入新的密码"></Input>
                        </Form-item>
                    </Form>
                </Modal>
        </div>
    </b-page>
</template>

<script>
    import BPage from 'components/BPage';
    import CommonPassword from 'components/commons/password'; //密码输入框
    export default {
        components: { BPage,CommonPassword },
        data(){
            const validateUser = (rule, value, callback) => {
                if (!value) return callback(new Error('请输入手机号'));                
                else if(!this.$utils.RegexUtils('MOBILE',value)) return callback(new Error('请输入有效的11位手机号'+'\n(当前长度：'+value.length+'位)'));
                else{
                    this.$ajax(this.$api.common.userCheck,{"mobile": value},(RES)=>{
                        if(RES.code == 200) return callback(new Error('该手机号已被绑定'));
                        else callback();
                    },(error)=>{
                        callback();  
                    })
                }
            };
            const validateMessage = (rule, value, callback) => {
                if (!value) return callback(new Error('请输入短信验证码'));                
                else if(!this.$utils.RegexUtils('SMS',value)) return callback(new Error('请输入有效的6位短信验证码'+'(当前长度：'+value.length+'位)'));
                else if(!this.$utils.RegexUtils('MOBILE',this.formMobile.mobile)) return callback(new Error('请完善手机信息再填写验证码信息'));
                else {
                    this.$ajax(this.$api.common.verifyCode,{"mobile": this.formMobile.mobile,"code": value},(RES)=>{
                        if(RES.code == 400) return callback(new Error('验证码有误，请重输'));
                        else if(RES.code == 454) return callback(new Error('验证码已过期，请重发'));
                        else callback();
                    },(error)=>{
                        return callback(new Error('服务器出错，请稍后重试'));
                    })
                }
            };
            const validatePassword = (rule, value, callback) => {
                if (!value) return callback(new Error('请输入登录密码'));
                else if(!this.$utils.RegexUtils('ISPWD',value)) callback(new Error('请输入6-16位数字字母字符'));
                else callback();
            };
            const validatePasswordRepeat = (rule, value, callback) => {
                if (!value) return callback(new Error('请确认登录密码'));
                else if(this.formPassword.password != this.formPassword.passwordRepeat) callback(new Error('与设置登录密码不一致，请重输'));
                else callback();
            };
            return {
                user: '',
                contactName: '',
                companyName: '',
                mobile: '',
                mobileModal: false,
                loadingMobile: true,
                formMobile: {
                    mobile: '',
                    code: ''
                },
                ruleMobile: {
                    mobile: [
                        { validator: validateUser, trigger: 'blur' }
                    ],
                    code: [
                        { validator: validateMessage, trigger: 'blur' }
                    ],
                },
                sendState: false,//是否已发送验证码状态
                codeTime: 60,
                codeTimeFun: '',
                passwordModal: false,
                loadingPassword: true,
                formPassword: {
                    oldPassword: '',
                    password: '',
                    passwordRepeat: '',
                },
                rulePassword: {
                    oldPassword: [
                        { validator: validatePassword, trigger: 'blur' }   
                    ],
                    password: [
                        { validator: validatePassword, trigger: 'blur' }                 
                    ],
                    passwordRepeat: [
                        { validator: validatePasswordRepeat, trigger: 'blur' }                 
                    ],
                },
            }
        },
        created() {
            this.init();
        },
        methods: {
            init() {
                //获取当前账号信息
                this.$ajax(this.$api.account.detail,'',(RES)=>{
                    if(RES.content){
                        this.user = RES.content.licenseNo;
                        this.contactName = RES.content.contactName;
                        this.companyName = RES.content.name;
                        this.mobile = RES.content.mobile;
                    }
                },(error)=>{
                    console.log(error);
                    this.$Message.error('获取不到账号信息，请稍后再试');
                })
            },
            //弹出框确定按钮事件
            submitMobile() {
                this.$refs.formMobile.validate((valid) => {
                    if (valid) {
                        //调用重置手机接口
                        this.$ajax(this.$api.account.resetMobile,this.formMobile,(RES)=>{
                            console.log(RES);   
                            if(RES.code == 200){
                                this.$Message.success('修改绑定手机号成功,请重新登录');
                                setTimeout(()=>{
                                    this.$router.push('/');
                                },3000)
                            }
                                       
                            this.mobileModal = false;//隐藏弹出框       
                        },(error)=>{    
                            console.log(error);
                            this.$Message.error('修改绑定手机号失败，请稍后再试');
                            this.mobileModal = false;//隐藏弹出框
                        })   
                    } else {
                        this.mobileModal = true;//不隐藏弹出框

                        this.loadingMobile = false;//关闭loading按钮效果
                        this.$nextTick(() => {
                            this.loadingMobile = true;//延后开启loading按钮效果，为下次验证做准备
                        });
                    }
                })
            },
            //弹框显示隐藏事件
            toggleMobile(state) {
                //开启弹框时清空表单
                if(state) this.$refs.formMobile.resetFields();
            },
            getCode() {
                this.$refs.formMobile.validateField('mobile',(valid) => {
                    if (!valid) {
                        this.$ajax(this.$api.common.sendCode,{"mobile": this.formMobile.mobile},(RES)=>{
                            if(RES.code == 200){
                                this.$Message.success('验证码已发送，请留意手机短信');
                                this.sendState = true;
                                this.setCodeTimeFun();
                            }                        
                        },(error)=>{    
                            console.log(error);
                            this.$Message.error('验证码发送失败，请稍后再试');
                        })
                    }
                })
            },
            backwardCodeTime() {
                if(this.codeTime>0) this.codeTime--;
                else{
                    clearInterval(this.codeTimeFun);
                    this.sendState = false;
                }
            },
            setCodeTimeFun() {
                this.codeTimeFun = setInterval(this.backwardCodeTime,1000);
                this.codeTime = 60;
            },
            submitPassword() {
                console.log('submitPassword');
                this.$refs.formPassword.validate((valid) => {
                    if (valid) {
                        //调用重置手机接口
                        this.$ajax(this.$api.account.updatePassword,{
                            "oldPassword": this.formPassword.oldPassword,
                            "newPassword": this.formPassword.password
                        },(RES)=>{
                            console.log(RES);   
                            if(RES.code == 200){
                                this.$Message.success('修改密码成功,请重新登录');
                                this.passwordModal = false;//隐藏弹出框      
                                setTimeout(()=>{
                                    this.$router.push('/');
                                },3000)
                            }
                            else if(RES.code == 457){
                                this.$Message.error('旧密码不正确,请重新输入'); 

                                this.loadingPassword = false;//关闭loading按钮效果
                                this.$nextTick(() => {
                                    this.loadingPassword = true;//延后开启loading按钮效果，为下次验证做准备
                                });
                            }
                        },(error)=>{    
                            console.log(error);
                            this.$Message.error('修改密码失败，请稍后再试');
                            this.passwordModal = false;//隐藏弹出框
                        })   
                    } else {
                        this.passwordModal = true;//不隐藏弹出框

                        this.loadingPassword = false;//关闭loading按钮效果
                        this.$nextTick(() => {
                            this.loadingPassword = true;//延后开启loading按钮效果，为下次验证做准备
                        });
                    }
                })
            },
            togglePassword(state) {
                //开启弹框时清空表单
                if(state) this.$refs.formPassword.resetFields();
            },
            passwordChange(val) {
                this.formPassword.password = val;
            }
        }
    }
</script>

<style lang="less" rel="stylesheet/less">
    .account-page{      
        background-color: #fff;

        .account-header{
            height: 42px;
            line-height: 42px;
            padding: 0 22px;
            font-size: 16px;
            color: @text-color-title;
            border-bottom: 1px solid @color-Divider;
        }

        .account-body{
            margin: 22px 22px 0 50px;
            padding-bottom: 22px;

            li{
                line-height: 42px;
                font-size: 14px;
                &>div{
                    display: inline-block;

                    &:first-child{
                        width: 200px;
                        color: @color-Sub;
                    }

                    &:last-child{
                        color: @color-Content;

                        button{
                            color: @color-Primary;
                        }
                    }
                }
            }
        } 
    }
    .form-password{
        padding-right: 30px;
        .ivu-poptip,.ivu-poptip-rel{
            width: 100% !important;
        }
    }
</style>